﻿using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Media;
using Nop.Core.Domain.WindAlert;
using Nop.Services.Helpers;
using Nop.Services.Localization;
using Nop.Services.Media;
using Nop.Services.WindAlert;
using Nop.Web.Framework.Kendoui;
using Nop.Web.Framework.Security.Captcha;
using Nop.Web.Models.WindAlert;
using System;
using System.Linq;
using System.Web.Mvc;


namespace Nop.Web.Controllers
{
	public partial class WAlertController : BasePublicController
    {
        #region Fields
        private readonly IAlertService _alertService;
        private readonly IWorkContext _workContext;
        private readonly IWindDataService _windDataService;
        private readonly IDateTimeHelper _dateTimeHelper;
        private readonly ISpotService _spotService;
        private readonly IPictureService _pictureService;
        private readonly ILocalizationService _localizationService;
        private readonly IForecastDataService _forecastDataService;
        private readonly IWaveDataService _waveDataService;
        private readonly IWindAlertPictureService _windAlertPictureService;

        private readonly MediaSettings _mediaSettings;
        private readonly CaptchaSettings _captchaSettings;
        private readonly CustomerSettings _customerSettings;
        private readonly WindAlertSettings _windAlertSettings;

        private readonly IWindHelpers _windHelper;

        private Random random = new Random();
        #endregion

        #region Constructors

        public WAlertController(
            IAlertService alertService,
            IWorkContext workContext, 
            IWindDataService windDataService,
            IDateTimeHelper dateTimeHelper,
            ISpotService SpotService,
            IPictureService pictureService,
            IWindAlertPictureService windAlertPictureService,
            ILocalizationService localizationService,
            MediaSettings mediaSettings,
            CustomerSettings customerSettings,
            CaptchaSettings captchaSettings,
            IForecastDataService forecastDataService,
            IWaveDataService waveDataService,
            IWindHelpers windHelper,
            WindAlertSettings windAlertSettings)
        {
            this._alertService = alertService;
            this._workContext = workContext;
            this._windDataService = windDataService;
            this._dateTimeHelper = dateTimeHelper;
            this._spotService = SpotService;
            this._pictureService = pictureService;
            this._localizationService = localizationService;
            this._mediaSettings = mediaSettings;
            this._customerSettings = customerSettings;
            this._captchaSettings = captchaSettings;
            this._forecastDataService = forecastDataService;
            this._waveDataService = waveDataService;
            this._windHelper = windHelper;
            this._windAlertSettings = windAlertSettings;
            this._windAlertPictureService = windAlertPictureService;
        }

        #endregion

        #region Utilities

        [NonAction]
        protected bool IsCurrentUserRegistered()
        {
            return _workContext.CurrentCustomer.IsRegistered();
        }

        private AlertModel SetAlertOption(AlertModel model)
        {
            switch (model.AlertOptionId)
            {
                case 10:
                    model.IntensityString = _localizationService.GetResource("windalert.alert.WindIntensity");
                    model.ExampleString = _localizationService.GetResource("windalert.alert.WindExample");
                    break;
                case 20:
                    model.IntensityString = _localizationService.GetResource("windalert.alert.WaveIntensity");
                    model.ExampleString = _localizationService.GetResource("windalert.alert.WaveExample");
                    break;
                case 30:
                    model.IntensityString = "";
                    model.ExampleString = "";
                    break;
            }
            return model;
        }
        #endregion

        public ActionResult List()
        {
            var model = new AlertListModel();
            var alerts = _alertService.GetAlertsByCustomerId(_workContext.CurrentCustomer.Id);
            foreach (var a in alerts)
            {
                var alertModel = new AlertModel()
                {
                    Id = a.Id,
                    AlertOptionId  = a.AlertOptionId, 
                    SpotsGroupId  = a.SpotsGroupId, 
                    Intensity = a.Intensity,
                    SpotsGroup  = a.SpotsGroup,
                };
                switch (alertModel.AlertOptionId)
                { 
                    case 10:
                        model.WindAlerts.Add(alertModel);
                        break;
                    case 20:
                        model.WaveAlerts.Add(alertModel);
                        break;
                    case 30:
                        model.ForecastAlerts.Add(alertModel);
                        break;
                }
            }
            return View(model);
        }

        #region Create / Edit Delete
        public ActionResult Create(int alertOptionId = 10)
        {
            var model = new AlertModel();
            model.AlertOptionId = alertOptionId;
            //get alers
            var alerts = _alertService.GetAllSpotsGroups(alertOptionId);
            if(alerts == null)
                return RedirectToAction("List");
            if (alerts.Count > 1)
            {
                model.AvailableSpotsGroups.Add(new SelectListItem { Text = _localizationService.GetResource("windalert.alert.selectSpot"), Value = "0" });
            }
            foreach (var sg in alerts)
            {
                model.AvailableSpotsGroups.Add(new SelectListItem
                {
                    Text = sg.Name,
                    Value = sg.Id.ToString(),
                    Selected = sg.Id == model.SpotsGroupId
                });
            }
            model = SetAlertOption(model);
            return View(model);
        }

        [HttpPost]
        [CaptchaValidator]
        public ActionResult Create(AlertModel model, bool captchaValid)
        {
            //validate CAPTCHA
            if (_captchaSettings.Enabled && !captchaValid)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptcha"));
            }

            if (ModelState.IsValid)
            {

                var alert = new Alert();

                alert.CustomerId  = _workContext.CurrentCustomer.Id;
                alert.SpotsGroupId = model.SpotsGroupId;
                alert.Intensity = model.Intensity;
                alert.AlertOptionId = model.AlertOptionId;

                //check if exists
                var existingAlert = _alertService.CheckIfAlertExists(alert);
                if (existingAlert == null)
                {
                    _alertService.InsertAlert(alert);
                    return RedirectToAction("List");
                }
                else
                {
                    return RedirectToAction("Edit", new { Id = existingAlert.Id });
                }
             
            }
            var alerts = _alertService.GetAllSpotsGroups(model.AlertOptionId);
            
            if (alerts == null)
                return RedirectToAction("List");

            if (alerts.Count > 1)
            {
                model.AvailableSpotsGroups.Add(new SelectListItem { Text = _localizationService.GetResource("windalert.alert.selectSpot"), Value = "0" });
            }

            foreach (var sg in alerts)
            {
                model.AvailableSpotsGroups.Add(new SelectListItem
                {
                    Text = sg.Name,
                    Value = sg.Id.ToString(),
                    Selected = sg.Id == model.SpotsGroupId
                });
            }
            model = SetAlertOption(model);
            return View (model);
        }

        public ActionResult Edit(int id)
        {
            var alert = _alertService.GetAlertById(id);
            if (alert == null)
                return RedirectToAction("List");
            var model = new AlertModel() 
            { 
                 AlertOptionId = alert.AlertOptionId, 
                 Intensity = alert.Intensity, 
                 SpotsGroupId  = alert.SpotsGroupId,
            };

            var spotsGroup = _alertService.GetSpotsGroupById(model.SpotsGroupId);            
            model.AvailableSpotsGroups.Add(new SelectListItem
            {
                Text = spotsGroup.Name,
                Value = spotsGroup.Id.ToString(),
                Selected = spotsGroup.Id == model.SpotsGroupId
            });

            model = SetAlertOption(model);
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(AlertModel model)
        {
            var alert = _alertService.GetAlertById(model.Id);
            if (alert == null)
                return RedirectToAction("List");

            if (ModelState.IsValid)
            {
                alert.SpotsGroupId = model.SpotsGroupId;
                alert.Intensity = model.Intensity;
                alert.AlertOptionId = model.AlertOptionId;
                _alertService.UpdateAlert(alert);

                return RedirectToAction("List");
            }

            var spotsGroup = _alertService.GetSpotsGroupById(model.SpotsGroupId);            
            model.AvailableSpotsGroups.Add(new SelectListItem
            {
                Text = spotsGroup.Name,
                Value = spotsGroup.Id.ToString(),
                Selected = spotsGroup.Id == model.SpotsGroupId
            });

            model = SetAlertOption(model);
            return View(model);
        }

        public ActionResult Delete(int id)
        {
            var alert = _alertService.GetAlertById(id);
            if (alert == null)
                return RedirectToAction("List");

            _alertService.DeleteAlert(alert);

            return RedirectToAction("List");
        }

        #endregion

        #region Ajax calling
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetSpotsGroupsByAlertOptionId(string alertOptionId)
        {
            //this action method gets called via an ajax request
            if (String.IsNullOrEmpty(alertOptionId))
                throw new ArgumentNullException("alertOptionId");

           
                var alertOptionIdint = Convert.ToInt32(alertOptionId);
                var spotsGroups = _alertService.GetAllSpotsGroups(alertOptionIdint);
                var result = (from sg in spotsGroups
                              select new { id = sg.Id, name = sg.Name })
                              .ToList();

                if (result.Count > 1)
                {
                    result.Insert(0, new { id = 0, name = _localizationService.GetResource("windalert.alert.selectSpot") });
                }

                return Json(result, JsonRequestBehavior.AllowGet);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetStationsBySpotsGroupId(string spotsGroupId)
        {
            //this action method gets called via an ajax request
            if (String.IsNullOrEmpty(spotsGroupId))
                throw new ArgumentNullException("spotGroupId");


            var spotsGroupint = Convert.ToInt32(spotsGroupId);
            var spotsGroup = _alertService.GetSpotsGroupById(spotsGroupint);
            var result = (from s in spotsGroup.Spots
                          select new { id = s.Id, name = s.Name })
                          .ToList();

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        #endregion
    }

   
}
